<?php
ob_start();
session_start();

include 'top3.php';
include("utils.php");
main_content("mainBuySpace();");
if(!isset($_SESSION[siteuserId]) ||  $_SESSION[siteuserId]=='')
	echo '<script>window.location="index.php"</script>';
function mainBuySpace()
{
	if(isset($_REQUEST[start_date])){
		$_SESSION['start_date'] = $_REQUEST[start_date];
		$_SESSION['txtTotalCost'] = $_REQUEST['txtTotalCost'];
	}
	if($_REQUEST[id])
	{
		$_SESSION['adspaceid'] = $_REQUEST[id];
		$_SESSION['enddate'] =$_REQUEST[days];
		$_SESSION['duration'] =$_REQUEST[duration];
		$adSize = mysql_fetch_array(mysql_query("SELECT adSize FROM adspace_details where adspaceId ={$_SESSION['adspaceid']} "));
		$_SESSION['adSize'] = $adSize['adSize'];

	}

	// Start values coming from buyNetworkAds.php
	$_SESSION['startDate'] = $_REQUEST['startDate'];
	if(isset($_REQUEST['network_id'])){
		$_SESSION['network_id'] = $_REQUEST['network_id'];
	}
	
	if(isset($_POST['post_checking']))
	{
		$_SESSION['userId'] = $_SESSION[siteuserId]; //userId
		$_SESSION['adtargetType'] = $_POST['network_type']; //adtargetType
		$res = mysql_query("select networkBidType from network_master where networkId = '".$_POST['network_id']."'");
		$row = mysql_fetch_array($res);
		$_SESSION['adpriceUnit'] = $row['networkBidType']; //adpriceUnit
		$tem = mysql_query("select networkMinPrice from network_details where networkId = '".$_POST['network_id']."'");
		$row1 = mysql_fetch_array($tem);
		$_SESSION['adbidPrice'] = $row1['networkMinPrice'] ; //adbidPrice
		$_SESSION['targetedOn']=time();//now(); //targetedOn
	
	}
	// End values coming from buyNetworkAds.php

	if($_SESSION['langId']!=""){
		$langId=$_SESSION['langId'];
	}
	else{
		$langId="1";
	}
	// to get the type of ad query
	$get_type_id = $_SESSION['type_id'] ; //$_POST['typeid'];
	$res_type_query = mysql_query("select adspaceType from adspace_details where adspaceId = '".$get_type_id."' ");
	$row_type_query = mysql_fetch_array($res_type_query);
	if(isset($_POST['post_checking'])){
		$adtype_retrieve=$_POST['network_type'];
	}else{
		$adtype_retrieve=$row_type_query['adspaceType'];
		$msg = array();
		$validate = true;
		if($_FILES["file"]['name']){
			list($width, $height) = getimagesize($_FILES["file"]['tmp_name']);
			if($adtype_retrieve =='banner')
			{
			switch ($_REQUEST['adSize'])
				{
					case '728x90':
							if( $width >730 || $width<725){
								$msg[] = "Please upload banner width: 728px";
								$validate = false;
							}
							if($height>91 || $height<89)
							{
								$msg[] = "Please upload banner height: 90px";
								$validate = false;
							}
							if($_FILES["file"]['size']<91)
							{
								$msg[] = "Please upload banner max size: 90k";
								$validate = false;
							}
						break;
					case '184x360':
							if( $width >185 || $width<183){
								$msg[] = "Please upload banner width: 184px";
								$validate = false;
							}
							if($height>361 || $height<358)
							{
								$msg[] = "Please upload banner height: 360px";
								$validate = false;
							}
							if($_FILES["file"]['size']<91)
							{
								$msg[] = "Please upload banner max size: 90k";
								$validate = false;
							}
						break;	
					case '160x100':
							if( $width >161 || $width<158){
								$msg[] = "Please upload banner width: 160px";
								$validate = false;
							}
							if($height>101 || $height<99)
							{
								$msg[] = "Please upload banner height: 100px";
								$validate = false;
							}
							if($_FILES["file"]['size']<91)
							{
								$msg[] = "Please upload banner max size: 90k";
								$validate = false;
							}
						break;	
					case '468x60':
							if( $width >468 || $width<466){
								$msg[] = "Please upload banner width: 468px";
								$validate = false;
							}
							if($height>61 || $height<60)
							{
								$msg[] = "Please upload banner height: 60px";
								$validate = false;
							}
							if($_FILES["file"]['size']<91)
							{
								$msg[] = "Please upload banner max size: 90k";
								$validate = false;
							}
						break;	
					case '120x240':
							if( $width >121 || $width<120){
								$msg[] = "Please upload bannerwidth: 120px";
								$validate = false;
							}
							if($height>241 || $height<240)
							{
								$msg[] = "Please upload banner height: 240px";
								$validate = false;
							}
							if($_FILES["file"]['size']<91)
							{
								$msg[] = "Please upload banner max size: 90k";
								$validate = false;
							}
						break;	
					default:
						break;
				}
			}
				if($_FILES["file"]["error"] > 0)
				{
					$msg[] = "upload file error.";
					$validate = false;
				}
			if($validate)
			{
				$file_name = $_FILES["file"]["name"];
				$extension = explode('.',$file_name);  
				$image = $_SESSION[siteuserId] .".".$extension[1];
				move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_SESSION[siteuserId] .".".$extension[1]);
				
			}else{
				$message="";
				foreach($msg as $item)
				{
					$message.="<div style='width:100%;color:red;height:20px;text-align:left;'>".$item."</div>";
				}
			}
		}
	}
	
		// End of file upload query
		if(isset($_REQUEST[addtocart]))
		{
			$val_split_date = $_POST['duration'];
			$split_date = explode(':',$val_split_date);
			$end_date = $split_date[1];
			if($start_date == '')
			{
				$start_date = $_SESSION['start_date'];
			}
			$split_duration = explode(',',$_REQUEST[enddate]);
			$duration = $split_duration[0];
			$total_amount = $split_duration[1];
			$fetSiteID = mysql_fetch_array(mysql_query("select adsiteId from adspace_master where  adspaceId='".$_REQUEST[adspaceid]."'"));
			$fetspaceType = mysql_fetch_array(mysql_query("select adspaceType from adspace_details where  adspaceId='".$_REQUEST[adspaceid]."'"));
			$fetSiteType = mysql_fetch_array(mysql_query("select adSiteType from adsite_master where  adsiteId='".$fetSiteID[adsiteId]."'"));
			$duration_cart=$_REQUEST['enddate'];
			$explode_duration_cart=explode(",",$duration_cart);
			$duratioN_query=$explode_duration_cart[0];
			$fetPrice = mysql_fetch_array(mysql_query("select ammount from adspace_price where  adspaceId='".$_REQUEST[adspaceid]."' and duration='".$duratioN_query."'"));
			$price = number_format($fetPrice[0]*$duratioN_query, 2, '.', '');
			$sqlAdMaster = "insert into advertise_master set 
				langId='".$langId."',
				adTitle='".$_REQUEST[txtHeadline]."',
				adTitle_personal='".$_REQUEST['txtAdName']."',
				adType='".$fetSiteType['adSiteType']."',
				destinationUrl='".$_REQUEST['txtUrl']."',
				startDate=now(),
				endDate='".$end_date."',
				adPrice='".$price."',
				ad_image = '".$_REQUEST['image']."',
				siteuserId='".$_SESSION[siteuserId]."'";
			
			if(mysql_query($sqlAdMaster))
			{
				$insertid = mysql_insert_id();
				$sqlAdDetails = "insert into advertise_details set 
				advertiseId='".$insertid."',
				adsiteId='".$fetSiteID[adsiteId]."',
				adspaceId='".$fetSiteID['adsiteId']."',
				adDisplayType ='".$fetspaceType[adspaceType]."',
				networkId = '".$_SESSION['network_id']."',
				clicks_to_purchase = '".$split_duration[1]."' ";
				mysql_query($sqlAdDetails);
				$sql_TempOrder = "insert into tblordertemp set 
				advertiseId='".$insertid."',
				session_id='".session_id()."',
				siteuserId='".$_SESSION['siteuserId']."',
				adsiteId  ='".$fetSiteID['adsiteId']."',
				adspaceId='".$_REQUEST['adspaceid']."',
				adspace_price ='".$price."',
				total_amount='".$price."',
				order_date=now(),
				Quentity='1'";
				mysql_query($sql_TempOrder)or die(mysql_error());
				echo '<script>window.location="cart.php?tab=buy_ads&subMenu=1"</script>';	
			}
		}

?>
<script>

function submit_browse_form()
{
document.getElementById('frmAvertise').submit();
return true;
}

function main_page()
{
window.location="buy_spaceNew.php" ;
}

function showhidSelectBox(mode)
{
if(mode!='none')
{

	document.getElementById('txtUrl').value=document.getElementById('selExistingAd').value;

}
else
{

	document.getElementById('txtUrl').value='';
document.getElementById('txtUrl').readOnly=false;
}
	document.getElementById('tdExistingAd').style.display=mode;
}



function validation(type_id)
{
 //alert(type_id);
var txtHeadline = document.getElementById("txtHeadline").value;
var txtUrl = document.getElementById("txtUrl").value;

if(type_id=='text'){
var text_description = document.getElementById("text_description").value; 

if(text_description != "")    {
        document.getElementById("validate_text_description").style.display="none";
    }
}

if(txtHeadline != "")    {
        document.getElementById("txtHeadline_validate").style.display="none";
    }

if(txtUrl != "" || txtUrl != "http://")    {
        document.getElementById("txtUrl_validate").style.display="none";
    }


if(txtHeadline == "")    {
        document.getElementById("txtHeadline_validate").style.display="block";
        //document.getElementById("txtHeadline_validate").innerHTML="Please Enter Headline!";
        document.getElementById("txtHeadline").focus();
        return false;
    }

if(type_id=='text'){
if(text_description == "")    {
        document.getElementById("validate_text_description").style.display="block";
        document.getElementById("validate_text_description").innerHTML="Please Enter Desc!";
        document.getElementById("text_description").focus();
        return false;
    }
}


if(txtUrl == "" || txtUrl == "http://")    {
        document.getElementById("txtUrl_validate").style.display="block";
        //document.getElementById("txtUrl_validate").innerHTML="Please Enter Destination Url!";
        document.getElementById("txtUrl").focus();

    
        return false;
    }

if(txtUrl != "")    {
	
	var v = new RegExp();
	v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
	if (!v.test(document.getElementById("txtUrl").value)) {
		alert("You must supply a valid URL.");
        document.getElementById("txtUrl").focus();
	return false;					      }
        
    		    }		


return true;
}

function preview_heading()
{
document.getElementById("prev_heading").value = document.getElementById("txtHeadline").value;
document.getElementById("prev_heading").innerHTML= document.getElementById("txtHeadline").value;
document.getElementById("prev_heading").style.display = 'block';
}

function preview_text_description_func()
{
document.getElementById("preview_text_description").value = document.getElementById("text_description").value;
document.getElementById("preview_text_description").innerHTML= document.getElementById("text_description").value;
document.getElementById("preview_text_description").style.display = 'block';
}

function una_dis(landing_val)
{
	//alert(landing_val);
	
// 	if(document.getElementById('landing_url').value != "select")
// 	{
	//document.getElementById('txtUrl').disabled=true;
	var arr=landing_val.split("-");
	//alert(arr[0]);
	//alert(arr[1]);
	document.getElementById('show_url').style.display='';
	document.getElementById('show_url').innerHTML='<a href='+arr[1]+'>'+arr[1]+'</a>';
	//}

// 	else {
// 	document.getElementById('txtUrl').disabled=false; 
// var arr=landing_val.split("-");
// 	document.getElementById('show_url').style.display='block';
// 	document.getElementById('show_url').innerHTML=arr[1];
	//}


}

function retrieve_data(id)
{
var id = id;
var xmlHttp;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
var res = xmlHttp.responseText;
//delete_garbage_network();
//alert(xmlHttp.responseText);

var allVal=new Array();

allVal = res.split(",");
//alert("Count--->"+allVal.length);ram
document.getElementById('txtHeadline').value = allVal[0];
document.getElementById('txtAdName').value = allVal[1];
document.getElementById('txtUrl').value = allVal[2];

      }
    }

  xmlHttp.open("GET","retrieve_ad_data.php?id="+id,true);
  xmlHttp.send(null);
  return false; 
}


function hidelanding()
{

document.getElementById('landing_url').style.display = 'none';
document.getElementById('landing_url_dd').style.display = 'none';
document.getElementById('nlp').style.display = 'none';
document.getElementById('nlp1').style.display = 'none';

}

function showlanding()
{
document.getElementById('landing_url').style.display = 'block';
document.getElementById('landing_url_dd').style.display = 'block';
document.getElementById('nlp').style.display = 'block';
document.getElementById('nlp1').style.display = 'block';
}
</script>

<input type="hidden" name="hidAdSpaceId" id="hidAdSpaceId" value="<?php echo $adspaceID;?>">
<input type="hidden" name="hidDelAdSpaceId" id="hidDelAdSpaceId" value="<?php echo $fetFavId[0];?>">
<table width="90%" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td valign="top" align="center"><table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
                  <tr>
                    <td width="20%" valign="top"><?php include("left_pannel.php"); ?></td>
                    <td width="10px">&nbsp;</td>
                    <td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                            <tr>
                              <td width="11"><img src="images/PinkBorderTopLeft.jpg" alt="" width="11" height="11"></td>
                              <td class="PinkBoxTopBg"><img src="images/spacer.gif" alt="" width="10" height="11"></td>
                              <td width="11"><img src="images/PinkBorderTopRight.jpg" alt="" width="11" height="11"></td>
                            </tr>
                        </table></td>
                      </tr>
                      <tr>
                        <td class="PinkTwosideBorder" valign="top"><table cellspacing="4" cellpadding="4" border="0">
              <TR>
                <TD align="left" colspan="9"><font class="sky font-14"><strong>1.Create Your Ad</strong></font>&nbsp;2.&nbsp;Shopping Cart&nbsp;3.&nbsp;Payment&nbsp;4.&nbsp;Your Order&nbsp;5.&nbsp;Order Confirmation </TD>
              </TR>
              <TR>
                <TD align="left">&nbsp;</TD>
              </TR>
              <tr>
              	<td colspan="9"><?php if(!empty($message)) { echo $message;} ?></td>
              </tr>
              <TR>
                <TD align="left"><table style="border:#CCCCCC 1px solid;" cellspacing="0" cellpadding="0">
                    <tr>
                      <td><!--LEFT TD-->
                        <table cellspacing="0" cellpadding="0" border="0">
                          <form name="frmAvertise" method="POST" action="" enctype="multipart/form-data" id="frmAvertise">
                          
                          <input type="hidden" name="duration" value="<?php echo $_SESSION['duration'];?>">
                          <input type="hidden" name="enddate" value="<?php echo $_SESSION['enddate'];?>">
                          <input type="hidden" name="adspaceid" value="<?php echo $_SESSION['adspaceid'];?>">
                          <input type="hidden" name="image" value=<?php echo $image; ?> >
                          <input type="hidden" name="adSize" value=<?php echo $_SESSION['adSize'];?>> 
                          <tr>
                          
                          <td valign="top" align="left"><table cellpadding="5" cellspacing="2" border="0">
                              <tr>
                                <td width="300" class="sitename" style="border-right:#cccccc 1px solid;" colspan="2">Create Your Ad</td>
                              </tr>

<?php
			$query_adtype="select * from advertise_details where adDisplayType = '".$adtype_retrieve."'  ";
			
			$res_adtype=mysql_query($query_adtype);

			if($_SESSION['site_type'] == 'WEB')
			{
 			?>
                              <TR>
                                <TD align="right"><input checked="true" onclick="showhidSelectBox('none')" type="radio" name="radSelectAd" id="radSelectAd1" checked="true" ></TD>
                                <td align="left"><strong>Create Your Ad</strong></td>
                              </tr>

                              <TR>
                                <TD align="right"><input onclick="showhidSelectBox('')"  type="radio" name="radSelectAd" id="radSelectAd2"></TD>
                                <td align="left"><strong>Use An Existing Ad</strong></td>
                              </tr>

                              <tr>
                                <TD colspan="2" id="tdExistingAd" style="display:none;">&nbsp;
                                  <select name="selExistingAd" id="selExistingAd" onchange="return retrieve_data(this.value);">
                                    <?php
						  while($row_adtype= mysql_fetch_array($res_adtype)){
						  $q = "select * from advertise_master where advertiseId = ".$row_adtype['advertiseId']." and siteuserId=".$_SESSION['siteuserId']." ";
						  $res = mysql_query($q);
						  $row = mysql_fetch_array($res);
                                    ?>
                                    <option value="<?php echo $row['advertiseId']; ?>"> <?php echo $row['adTitle'];?></option>
                                    <?php
                                        }
                                        ?>
                                  </select>
                                  <!--left td-->
                                </TD>
                              </tr>
                              <?php
			}
			
						
			if($_SESSION['site_type'] == 'MOBILE')
			{
			$query_web = "select * from adspace_landing_page where UserId = ".$_SESSION[siteuserId]." " ;
			$res_web = mysql_query($query_web);
			$num_rows = mysql_num_rows($res_web);
			?>

			<TR>
                                <TD align="left"><input checked="true" onclick="hidelanding();" type="radio" name="existing_mobile_ad" id="existing_mobile_ad" checked="true" ><strong>An existing mobile page</strong></td>
                              </tr>

                              <TR>
                                <TD align="left"><input onclick="showlanding();"  type="radio" name="existing_mobile_ad" id="radSelectAd2"><strong>2 in 1 hosted Landing Page</strong></td>
                              </tr>
			<?php 

			if($num_rows > 0) {
			?>
			
                              <tr id="landing_url" style="display:none;">
                                <TD colspan="2">&nbsp;Landing URL</TD>
                              </tr>
                              <tr id="landing_url_dd" align="left" style="display:none;">
                                <TD colspan="2">&nbsp;
                                  <seLECT name="landing_url" id="landing_url" onchange="return una_dis(this.value);">
                                    <option value="select">Select</option>
                                    <?php while($row_web = mysql_fetch_array($res_web)){ ?>
                                    <option value="<?php echo $row_web['landingId']."-".$row_web['landing_url'] ?>"><?php echo $row_web['pageTitle']; ?></option>
                                    <?php } ?>
                                  </seLECT>
					
                                </TD>
                              </tr>
				<tr id="nlp1"><TD id="show_url" style="display:none;"></TD></tr>
			 	<tr id="nlp" style="display:none;"><TD><a href="create_landing_page.php">Create New Landing Page</a></TD></tr>
			
                              <?php } 

			}
			

			
   if($adtype_retrieve == 'text' || $adtype_retrieve == 'thumbnail'){ ?>
                              <tr>
                                <TD colspan="2">&nbsp;*Headline:</TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;
                                  <input type="text" name="txtHeadline" id="txtHeadline" onkeyup="return preview_heading();"></TD>
                                <TD colspan="2" id="txtHeadline_validate" style="display:none;">Please Enter Url!</TD>
                              </tr>
                              <?php } ?>
                              <?php if($adtype_retrieve == 'text'){ ?>
                              <tr>
                                <TD colspan="2">&nbsp;*Add Description</TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;
                                  <textareA name="text_description" id="text_description" onkeyup="return preview_text_description_func();"></textareA></TD>
                                <TD colspan="2" id="validate_text_description" style="display:none;">Please Enter Description !</TD>
                              </tr>
                              <?php } ?>
                              <?php if($adtype_retrieve == 'banner' || $adtype_retrieve == 'thumbnail'){ ?>
                              <tr>
                                <TD colspan="2">&nbsp;*Upload File:  (Max. 90 KB) (<?php echo $_SESSION['adSize']; ?> preferred)</TD>
                              </tr>
                              <tr>
                                <TD colspan="2"><input type="file" name="file" id="file" onchange="return submit_browse_form();" />
                                  <inpUT type="hidden" name="sahara" value="11">
                                </TD>
                              </tr>
                           
                              
                              <?php } ?> 

                              <tr>
<?php if(isset($_SESSION['site_type']) && $_SESSION['site_type'] == 'WEB') { ?>
                                <TD colspan="2">&nbsp;*Destination URL (http://):</TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;
                                  <input type="text" name="txtUrl" id="txtUrl" value="http://"></TD>
                                <TD colspan="2" id="txtUrl_validate" style="display:none;">Please Enter Destiny url!</TD>
                              </tr>
<?php } ?>
                              <tr>
                                <TD colspan="2">&nbsp;Ad Name (For personal reference)</TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;
                                  <input type="text" name="txtAdName" id="txtAdName"></TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;</TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;
                                  <input type="button" value="Cancel" onclick="return main_page();">
                                  &nbsp;
                                  <input type="submit" value="Proceed To Cart" name="addtocart" onclick="return validation('<?php echo $adtype_retrieve;?>');"></TD>
                              </tr>
                              <tr>
                                <TD colspan="2">&nbsp;</TD>
                              </tr>
                            </table></td>
                          <td width="50px" valign="top">&nbsp;</td>
                            <!--Middle TD-->
                            <td valign="top"><!--Right TD START-->
                              <table width="100%">
                                <tr valign="top">
                                  <td class="sitename" style="border-right:#cccccc 1px solid;" valign="top" align="center">Preview</td>
                                </tr>
                                <tr>
                                  <td align="center" id="prev_heading">Headline Goes Here</td>
                                </tr>
                                <?php if($adtype_retrieve == 'thumbnail'){ ?>
                                <tr>
                                  <td><imG src="upload/<?php echo $_SESSION[siteuserId]; ?>.<?php echo $extension[1]; ?>"></td>
                                </tr>
                                <?php } ?>
                                <?php if($adtype_retrieve == 'text'){ ?>
                                <tr>
                                  <td align="center" id="preview_text_description">Ad Description Goes Here</td>
                                </tr>
                                <?php } ?>
                                <?php if($adtype_retrieve == 'banner'){ ?>
                                <tr>
                                  <td><imG src="upload/<?php echo $_SESSION[siteuserId]; ?>.<?php echo $extension[1]; ?>" ></td>
                                </tr>
                                <?php } ?>
                                <tr>
                                  <td>Please note: The Preview will not display correctly if you do not set the "Text size" to "Normal" on your browser.</td>
                                </tr>
                              </table></td>
                            <!--Right TD END-->
                          </tr></form>
                        </table></td>
                    </tr>
                    
                    
                  </table></TD>
            </table></td>
                      </tr>
                      <tr>
                        <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                            <tr>
                              <td width="11"><img src="images/PinkBorderBottomLeft.jpg" alt="" width="11" height="11"></td>
                              <td class="PinkBoxBottomBg"><img src="images/spacer.gif" alt="" width="10" height="11"></td>
                              <td width="11"><img src="images/PinkBorderBottomRight.jpg" alt="" width="11" height="11"></td>
                            </tr>
                        </table></td>
                      </tr>
                    </table></td>
                    <td>&nbsp;</td>
                    </tr>
                </table></td>
              </tr>
            </table>
<?php
}
?>
